<?php

namespace app\common\service\merchant;
use app\common\cache\merchant\MerchantShopCache;
use app\common\model\Merchant\MerchantShopModel;
use app\common\service\setting\RegionService;

/**
 * 店铺管理
 */
class MerchantShopService
{
    /**
     * 添加、修改字段
     * @var array
     */
    public static $edit_field = [
        'id/d'=>null,//主键ID
        'title/s'=>'',//店铺名称
        'content/s'=>'',//内容
        'is_disable/d'=>0,//是否禁用，1是0否
        'is_delete/d'=>0,//是否删除，1是0否
        'merchant_id/d'=>null,//商家ID
        'setting_store_platform_id/d'=>null,//店铺平台
        'setting_store_type_id/d'=>null,//店铺类目
        'setting_store_flag_id/d'=>null,//店铺旗帜
        'flag_remark/s'=>'',//插旗备注
        'shop_wangwang/s'=>'',//店铺旺旺
        'shop_website/s'=>'',//店铺网址
        'shop_group_title/s'=>'',//分组名称
        'repurchase_days/d'=>0,//复购天数
        'delivery_people/s'=>'',//发件人
        'delivery_phone/s'=>'',//发件人号码
        'delivery_region_id/d'=>null,//发货地址
        'delivery_address/s'=>'',//详细地址
        'is_assistant/d'=>0,//小助手：0、关闭  1、开启
        'is_mer_rebate/d'=>0,//商反:0、关闭  1、开启
        'auth_status/d'=>0,//审核状态：0、待审核 1、审核通过 2、审核拒绝
        'auth_msg/s'=>null,//审核备注
        'auth_time/s'=>null,//审核时间
        'image_id/d'=>null,//缩略图
        'sort/d'=>250,//排序
        'remark/s'=>'',//备注
        'auth_end_time/s'=>null,//授权到期时间
        'shop_group_id/d'=>0,
    ];
    /**
     * 店铺管理列表
     *
     * @param array  $where 条件
     * @param int    $page  页数
     * @param int    $limit 数量
     * @param array  $order 排序
     * @param string $field 字段
     *
     * @return array
     */
    public static function list($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $model = new MerchantShopModel();
        $pk = $model->getPk();
        if (empty($field)) {
            $field = 'id,title,content,is_disable,create_time,update_time,merchant_id,setting_store_platform_id,setting_store_type_id,setting_store_flag_id,flag_remark,shop_wangwang,shop_website,shop_group_title,repurchase_days,delivery_people,delivery_phone,delivery_region_id,delivery_address,is_assistant,is_mer_rebate,auth_status,auth_msg,auth_time,image_id,sort,remark,auth_end_time,shop_group_id';
        }
        if (empty($order)) {
            $order = ['merchant_id'=>'desc','auth_status'=>'asc','setting_store_platform_id'=>'asc','sort'=>'asc',$pk => 'desc'];
        }
        $with = ['merchant'=>function ($query) {
            $query->field('id,title');
        },'platform'=>function ($query) {
            $query->with(['image'])->hidden(['image'])->append(['image_url'])->field('id,title,image_id');
        },'type'=>function ($query) {
            $query->field('id,title');
        },'group'=>function ($query) {
            $query->field('id,title');
        },'flag'=>function ($query) {
            $query->with(['image'])->hidden(['image'])->append(['image_url'])->field('id,title,image_id');
        }];
        $append = $hidden = [];
        if (strpos($field, 'image_id') !== false) {
            $with[]   = $hidden[] = 'image';
            $append[] = 'image_url';
        }
        if ($page == 0 || $limit == 0) {
            return $model->with($with)->append($append)->hidden($hidden)->field($field)->where($where)->order($order)->select()->toArray();
        }
        $count = $model->where($where)->count();
        $pages = ceil($count / $limit);
        $list = $model->with($with)->append($append)->hidden($hidden)->field($field)->where($where)->page($page)->limit($limit)->order($order)->select()->toArray();
        //发货地区处理
        foreach ($list as $k => &$v) {
            $v['delivery_region_title'] = "";
            if($v['delivery_region_id']){
                $region = RegionService::info($v['delivery_region_id']);
                if(isset($region['region_fullname'])){
                    $v['delivery_region_title'] = $region['region_fullname'];
                }
            }
        }
        return compact('count', 'pages', 'page', 'limit', 'list');
    }
    /**
     * 查询店铺信息
     *
     * @param array  $where 条件
     * @param int    $page  页数
     * @param int    $limit 数量
     * @param array  $order 排序
     * @param string $field 字段
     *
     * @return array
     */
    public static function getListByPromotion($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $model = new MerchantShopModel();
        $pk = $model->getPk();
        if (empty($field)) {
            $field = 'id,title,create_time,auth_status';
        }
        if (empty($order)) {
            $order = ['merchant_id'=>'desc','auth_status'=>'asc','sort'=>'asc',$pk => 'desc'];
        }
        if ($page == 0 || $limit == 0) {
            return $model->field($field)->where($where)->order($order)->select()->toArray();
        }
        $count = $model->where($where)->count();
        $pages = ceil($count / $limit);
        $list = $model->field($field)->where($where)->page($page)->limit($limit)->order($order)->select()->toArray();
        return compact('count', 'pages', 'page', 'limit', 'list');
    }
    /**
     * 店铺管理信息
     *
     * @param int  $id   店铺管理id
     * @param bool $exce 不存在是否抛出异常
     *
     * @return array|Exception
     */
    public static function info($id, $exce = true)
    {
        $info = MerchantShopCache::get($id);
        if (empty($info)) {
            $model = new MerchantShopModel();
            $with = ['merchant'=>function ($query) {
                $query->field('id,title');
            },'platform'=>function ($query) {
                $query->field('id,title');
            },'type'=>function ($query) {
                $query->field('id,title');
            },'flag'=>function ($query) {
                $query->field('id,title');
            }];
            $info = $model->with($with)->find($id);
            if (empty($info)) {
                if ($exce) {
                    exception('店铺不存在：' . $id);
                }
                return [];
            }
            $info = $info->append(['image_url'])->hidden(['image'])->toArray();
            //发货地区处理
            $info['delivery_region_title'] = "";
            if($info['delivery_region_id']){
                $region = RegionService::info($info['delivery_region_id']);
                if(isset($region['region_fullname'])){
                    $info['delivery_region_title'] = $region['region_fullname'];
                }
            }
            MerchantShopCache::set($id, $info);
        }
        return $info;
    }
    /**
     * 店铺管理添加
     *
     * @param array $param 店铺管理信息
     *
     * @return array|Exception
     */
    public static function add($param)
    {
        $model = new MerchantShopModel();
        $pk = $model->getPk();
        unset($param[$pk]);
        $param['create_uid']  = user_id();
        $param['create_time'] = datetime();
        $model->save($param);
        $id = $model->$pk;
        if (empty($id)) {
            exception();
        }
        $param[$pk] = $id;
        return $param;
    }
     /**
     * 店铺管理修改
     *
     * @param int|array $ids   店铺管理id
     * @param array     $param 店铺管理信息
     *
     * @return array|Exception
     */
    public static function edit($ids, $param = [])
    {
        $model = new MerchantShopModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $update_uid = user_id();
        if($update_uid<=0){
            $update_uid=mer_user_id();
        }
        $param['update_uid']  = $update_uid;
        $param['update_time'] = datetime();
        $res = $model->where($pk, 'in', $ids)->update($param);
        if (empty($res)) {
            exception();
        }
        $param['ids'] = $ids;
        MerchantShopCache::del($ids);
        return $param;
    }
    /**
     * 店铺管理删除
     *
     * @param array $ids  店铺管理id
     * @param bool  $real 是否真实删除
     *
     * @return array|Exception
     */
    public static function dele($ids, $real = false)
    {
        $model = new MerchantShopModel();
        $pk = $model->getPk();
        if ($real) {
            $res = $model->where($pk, 'in', $ids)->delete();
        } else {
            $update = delete_update();
            $res = $model->where($pk, 'in', $ids)->update($update);
        }
        if (empty($res)) {
            exception();
        }
        $update['ids'] = $ids;
        MerchantShopCache::del($ids);
        return $update;
    }
}
